using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using System.Diagnostics;
using System.IO;

namespace SiteSecurityManagement.FeatureReceiver
{
    class DeployResources:SPJobDefinition
    {
        #region Members
        [Persisted]
        private string sourcePath;
        #endregion

        #region Constructor/Destructor

        /// <summary>
        /// Initializes a new instance of the <see cref="DeployResources"/> class.
        /// </summary>
        public DeployResources()
            : base()
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="DeployResources"/> class.
        /// </summary>
        /// <param name="jobName">Name of the job.</param>
        /// <param name="webApp">The web app.</param>
        /// <param name="featureName">Name of the feature.</param>
        public DeployResources(string jobName, SPWebApplication webApp, string featureName)
            : base(jobName, webApp, null, SPJobLockType.Job)
        {
            //Determine the path to the feature's resource files
            sourcePath=string.Format("{0}\\FEATURES\\{1}\\",
                                     SPUtility.GetGenericSetupPath("Template"),
                                     featureName);
        }
        #endregion

        #region Properties
        #endregion

        #region Methods
        public override void Execute(Guid targetInstanceId)
        {
            try 
            {
                SPWebApplication webApp = (SPWebApplication)this.Parent;

                foreach (SPUrlZone zone in webApp.IisSettings.Keys)
                {
                    //the settings of the iis application to update
                    SPIisSettings oSettings = webApp.IisSettings[zone];

                    //determine the dest path
                    string destPath = Path.Combine(oSettings.Path.ToString(), "App_GlobalResources");
                    string[] filePaths = Directory.GetFiles(sourcePath, "*.resx");

                    //Copy Files
                    foreach (string filePath in filePaths)
                    {
                        string fileName = Path.GetFileName(filePath);
                        File.Copy(filePath, Path.Combine(destPath, fileName), true);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Failed to copy resources");
                Debug.WriteLine(e);
                throw;
            }
        }
        #endregion
    }
}
